const jwt = require('jsonwebtoken')

const { createUser, getUserInfo, updateById } = require('../service/user.service');
const { userRegisterError } = require('../constant/err.type')

const { JWT_SECRET } = require('../config/config.default')

class UserController {
    async register(ctx, next) {
        // 1.获取数据
        // console.log(ctx.request.body);
        const {
            user_name, password
        } = ctx.request.body;


        // 2.操作数据库
        const res = await createUser(user_name, password);
        console.log(res);

        try {
            ctx.body = {
                code: 200,
                message: '用户注册成功',
                result: {
                    id: res.id,
                    user_name: res.user_name
                }
            }
        } catch (error) {
            console.log(error);
            ctx.app.emit('error', userRegisterError, ctx);
        }

    }
    async login(ctx, next) {
        const { user_name } = ctx.request.body
        // ctx.body = `登录成功,${user_name}`
        // 1.获取用户信息
        try {
            // 重返回结果对象中剔除password属性，将剩下的属性放到res对象里面
            const { password, ...res } = await getUserInfo({ user_name });
            ctx.body = {
                code: 0,
                massage: '登录成功',
                result: {
                    // 颁发token
                    token: jwt.sign(res, JWT_SECRET, { expiresIn: '1d' })
                }
            }
        } catch (err) {
            console.error('登录失败');
        }
    }
    async changePassword(ctx, next) {
        console.log(ctx);
        // 获取数据
        // 操作数据库
        // 返回结果
        const id = ctx.state.user.id
        const password = ctx.request.body.password
        // console.log(id, password);
        if (await updateById({ id, password })) {
            ctx.body = {
                code: 0,
                message: '修改密码成功',
                result: ''
            }
        } else {
            ctx.body = {
                code: '10007',
                message: '修改密码失败',
                result: ''
            }
        }

    }
}

module.exports = new UserController()